package com.klun.designMode.proxy.CGlibProxy1;

import com.klun.designMode.proxy.JDKProxy1.UserService;
import com.klun.designMode.proxy.JDKProxy1.UserServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGlibProxy - 动态代理
 */
public class MyBeanFactory {
    //cglib代理
    public static UserService createUserService() {
        //目标类
        final UserService userService = new UserServiceImpl();
        /**
         * 代理类
         * 回掉函数中的intercept同jdk动态代理的invoke方法
         * 4个参数，前三个同jdk动态代理的参数
         * 第四个参数：methodProxy是目标类的方法的代理
         *
         */
        //1.1核心类
        Enhancer enhancer = new Enhancer();
        //1.2确定父类
        enhancer.setSuperclass(UserService.class);
        //1.3设置回掉函数
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("执行前");
                Object invoke = method.invoke(userService, args);
                System.out.println("执行后");
                return invoke;
            }
        });
        //1.4创建代理对象
        UserService proxyUserService = (UserService) enhancer.create();
        return proxyUserService;
    }
}
